<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //?首尾节流：是指在时间间隔内的第一次触发事件和最后一次触发事件时执行函数，然后在间隔时间内忽略所有的其他触发事件
    function throttleBoth(fn,delay) {
        let flag = false
        let time = Date.now()
        let timer = null
        return function (...args) {
            const now = Date.now()
            //? 第一次触发 首节流
            if (flag === false) {
                console.log('第一次')
                fn(...args)
                flag = true
            }
            //? 非第一次
            else {
                console.log('节流')
                //? 还在时间间隔内 尾节流
                if (now - time <= delay) {
                    if (timer) {
                        clearTimeout(timer)
                        timer = null
                    }
                    timer = setTimeout(() => {
                        fn(...args)
                    },delay + time - now)
                }
            }
        }
    }
    function testThrottleBoth() {
        console.log('throttleBoth test start');
        const throttleFunc = throttleBoth(function() {
            console.log('throttleBoth function called');
        }, 1000);
        throttleFunc();
        setTimeout(throttleFunc, 500);
        setTimeout(throttleFunc, 800);
        setTimeout(throttleFunc, 1500);
        setTimeout(throttleFunc, 3500);
    }
    testThrottleBoth();
</script>
</body>
</html>
